﻿using MySql.Data.MySqlClient;
using ExpressHelps.Model;
using System.Text;
using System.Data;
using System.Linq.Expressions;

namespace ExpressHelps.DAL
{
    public static class TaskRepository
    {
        public static string mysqlStr = "userid=zero_register;password=bd0247e3a0cc4ea0;server=mysql.sqlpub.com;database=express_helps;";
        //保存订单
        public static void SaveTask(Tasks task)
        {
            //数据库存储逻辑
            //接受task对象，将其存储进数据库
            using (MySqlConnection connection = new MySqlConnection(mysqlStr))
            {
                try
                {
                    connection.Open();
                    //将task存进数据库中的表tasks中
                    string sql = "INSERT INTO tasks " 
                        +"(task_id, task_type, task_description, task_publisher_id, task_receiver_id, task_address, task_publish_time, task_receive_time, task_isreceiver, task_iscomplete, task_money) " 
                        +"VALUES (@TaskId, @TaskType, @TaskDescription, @TaskPublisherId, @TaskReceiverId, @TaskAddress, @TaskPublishTime, @TaskReceiveTime, @TaskIsReceiver, @TaskIsComplete, @TaskMoney)";
                    //参数化查询，防止sql注入
                    using (MySqlCommand cmd = new MySqlCommand(sql, connection))
                    {
                        cmd.Parameters.AddWithValue("@TaskId", task.task_id);
                        cmd.Parameters.AddWithValue("@TaskType", task.task_type.ToString());
                        cmd.Parameters.AddWithValue("@TaskDescription", task.task_description);
                        cmd.Parameters.AddWithValue("@TaskPublisherId", task.task_publisher_id);
                        cmd.Parameters.AddWithValue("@TaskReceiverId", task.task_receiver_id);
                        cmd.Parameters.AddWithValue("@TaskAddress", task.task_address);
                        cmd.Parameters.AddWithValue("@TaskPublishTime", task.task_publish_time);
                        cmd.Parameters.AddWithValue("@TaskReceiveTime", task.task_receive_time);
                        cmd.Parameters.AddWithValue("@TaskIsReceiver", task.task_isreceiver? 1 : 0);
                        cmd.Parameters.AddWithValue("@TaskIsComplete", task.task_iscomplete? 1 : 0);
                        cmd.Parameters.AddWithValue("@TaskMoney", task.task_money);
                        cmd.ExecuteNonQuery();
                        EventMediator.TriggerLogEvent($"创建订单成功！订单号为：{LoginUsers.taskId - 1}");
                    }
                }
                catch (Exception ex)
                {
                    //调用主线程的回调函数，打印数据库连接信息
                    EventMediator.TriggerLogEvent(ex.Message);
                }
            }

        }
        //通过Id查找订单
        public static Tasks GetTaskById(int taskId)
        {
            Tasks task = new Tasks();
            using(MySqlConnection connection = new MySqlConnection(mysqlStr))
            {
                try
                {
                    connection.Open();
                    string sql = "SELECT * FROM tasks WHERE task_id = @TaskId";
                    using(MySqlCommand cmd = new MySqlCommand(sql, connection))
                    {
                        //防止SQL注入
                        cmd.Parameters.AddWithValue("@TaskId", taskId);
                        MySqlDataReader reader = cmd.ExecuteReader();
                        if(reader.Read())
                        {
                            task.task_id = reader.GetInt32(0);
                            task.task_type = (Tasks.TaskType)Enum.Parse(typeof(Tasks.TaskType), reader.GetString(1), true);
                            task.task_description = reader.GetString(2);
                            task.task_publisher_id = reader.GetInt32(3);
                            task.task_receiver_id = reader.GetInt32(4);
                            task.task_address = reader.GetString(5);
                            task.task_publish_time = reader.GetDateTime(6);
                            task.task_receive_time = reader.GetDateTime(7);
                            task.task_isreceiver = reader.GetBoolean(8);
                            task.task_iscomplete = reader.GetBoolean(9);
                            task.task_money = reader.GetInt32(10);
                        }
                    }
                }
                catch(Exception ex)
                {
                    EventMediator.TriggerLogEvent(ex.Message);
                }
            }

            return task;
        }
        /*
        //找出所有的未被接取的订单
        public static List<Tasks> GetTasksUnreceived()
        {
            List<Tasks> taskList = new List<Tasks>();

            using (MySqlConnection connection = new MySqlConnection(mysqlStr))
            {
                try
                {
                    connection.Open();
                    string sql = "SELECT * FROM tasks WHERE task_isreceiver = @TaskIsReceived";
                    using(MySqlCommand cmd =  new MySqlCommand(sql, connection))
                    {
                        cmd.Parameters.AddWithValue("@TaskIsReceived", false);
                        MySqlDataReader reader = cmd.ExecuteReader();
                        while (reader.Read())
                        {
                            Tasks task = new Tasks();
                            task.task_id = reader.GetInt32(0);
                            task.task_type = (Tasks.TaskType)Enum.Parse(typeof(Tasks.TaskType), reader.GetString(1), true);
                            task.task_description = reader.GetString(2);
                            task.task_publisher_id = reader.GetInt32(3);
                            task.task_receiver_id = reader.GetInt32(4);
                            task.task_address = reader.GetString(5);
                            task.task_publish_time = reader.GetDateTime(6);
                            task.task_receive_time = reader.GetDateTime(7);
                            task.task_isreceiver = reader.GetBoolean(8);
                            task.task_iscomplete = reader.GetBoolean(9);
                            task.task_money = reader.GetInt32(10);
                            taskList.Add(task);
                        }
                    }
                }catch(Exception ex)
                {
                    EventMediator.TriggerLogEvent(ex.Message);
                }
            }
            return taskList;
        }
        */
        //找出所有未被接取的订单
        public static DataTable GetTasksUnreceived()
        {
            DataTable dt = new DataTable();
            try
            {
                using (MySqlConnection connection = new MySqlConnection(mysqlStr))
                {
                    connection.Open();
                    string sql = "SELECT * FROM tasks WHERE task_isreceiver = false";
                    using(MySqlDataAdapter ad = new MySqlDataAdapter(sql, mysqlStr))
                    {
                        ad.Fill(dt);
                    }
                }
            }catch(Exception ex)
            {
                EventMediator.TriggerLogEvent(ex.Message);
            }
            return dt;
        }
        //通过订单id接取订单，并且返回bool值，true表示接取成功，false表示接取失败，需配合GetTaskById使用
        public static bool ReceiveTask(int taskId)
        {
            try{
                using(MySqlConnection connection = new MySqlConnection(mysqlStr))
                {
                    connection.Open();
                    //直接进行数据更新
                    string sql = "UPDATE tasks SET task_receiver_id = @ReceiverId, task_receive_time = @NowTime, task_isreceiver = true WHERE task_id = @TaskId";
                    using(MySqlCommand cmd = new MySqlCommand(sql,connection))
                    {
                        //任务被本地登陆者接取，要判断是否与发布者一样
                        cmd.Parameters.AddWithValue("@ReceiverId", LoginUsers.userId);
                        cmd.Parameters.AddWithValue("@Nowtime", DateTime.Now.ToString());
                        cmd.Parameters.AddWithValue("@TaskId", taskId);
                        cmd.ExecuteNonQuery();
                        return true;
                    }
                }
            }catch(Exception ex)
            {
                EventMediator.TriggerLogEvent(ex.Message);
                return false;
            }


        }

    }
}